<!-- 委外订单管理 -->
<template>
  <div class="mod-config">
    <el-tabs v-model="tabValue" type="border-card" @tab-click="tabChange">
      <el-button-group style="margin-bottom: 10px;">
        <el-button type="primary" icon="el-icon-search" @click="searchHandle">查询</el-button>
        <el-button type="primary" icon="el-icon-delete" @click="searchReset">清空</el-button>
        <el-button v-if="tabValue == 'tab2'" type="primary" @click="exportExcel">导出成Excel</el-button>
      </el-button-group>
      <el-tab-pane label="未生成委外订单" name="tab1">
        <el-form inline label-width="100px" @keyup.enter.native="searchHandle">
          <el-form-item label="配镜单号">
            <el-input v-model="dataForm.saleBillId"></el-input>
          </el-form-item>
          <el-form-item label="制造商">
            <el-select v-model="dataForm.supplyId">
              <el-option v-for="item in supplyOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="销售部门">
            <el-select v-model="dataForm.deptId">
              <el-option v-for="item in deptOption" :value="item.id" :label="item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="配镜时间">
            <el-row>
              <el-col :span="11">
                <el-date-picker v-model="dataForm.createTimeStart" style="width: 100%;" value-format="yyyy-MM-dd"
                  :picker-options="timeOptionStart" @change="timeChangeEnd"></el-date-picker>
              </el-col>
              <el-col class="line" :span="2" style="text-align: center;">-</el-col>
              <el-col :span="11">
                <el-date-picker v-model="dataForm.createTimeEnd" style="width: 100%;" value-format="yyyy-MM-dd"
                  :picker-options="timeOptionEnd" @change="timeChangeStart"></el-date-picker>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="取镜时间">
            <el-row>
              <el-col :span="11">
                <el-date-picker v-model="dataForm.takeMirroTimeStart" style="width: 100%;" value-format="yyyy-MM-dd"
                  :picker-options="timeOptionStart" @change="timeChangeEnd"></el-date-picker>
              </el-col>
              <el-col class="line" :span="2" style="text-align: center;">-</el-col>
              <el-col :span="11">
                <el-date-picker v-model="dataForm.takeMirroTimeEnd" style="width: 100%;" value-format="yyyy-MM-dd"
                  :picker-options="timeOptionEnd" @change="timeChangeStart"></el-date-picker>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="配镜类型">
            <el-select v-model="dataForm.saleType">
              <el-option v-for="item in saleTypeOptions" :value="item.value" :label="item.label" :key="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="dataForm.viewGoodsName"></el-input>
          </el-form-item>
          <el-form-item label="顾客姓名">
            <el-input v-model="dataForm.customerName"></el-input>
          </el-form-item>
        </el-form>
        <div class="avue-crud">
          <div class="avue-crud">
            <el-table :data="firstList" border v-loading="dataListLoading" :max-height="tableHeight" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="saleBillId" label="配镜单号">
                <template slot-scope="scope">
                  <el-button type="text" @click="checkDetailByOrder(scope.row.saleBillId)">{{scope.row.saleBillId}}</el-button>
                </template>
              </el-table-column>
              <el-table-column prop="customerName" label="顾客姓名"> </el-table-column>
              <el-table-column prop="deptName" label="销售部门"> </el-table-column>
              <el-table-column prop="saleType" label="配镜类型">
                <template slot-scope="scope">
                  <!-- 1-隐形订做,2-框镜订做,3-隐形成品,4-框镜成品,5-辅料 -->
                  {{getSaleType(scope.row.saleType)}}
                </template>
              </el-table-column>
              <el-table-column prop="saleTime" label="配镜时间"></el-table-column>
              <el-table-column prop="takeMirroTime" label="取镜时间"></el-table-column>
              <el-table-column label="操作" fixed="right">
                <template slot-scope="scope">
                  <el-button v-if="permissions.eims_consign_add" type="text" icon="el-icon-edit" @click="openDialogConsignAdd(scope.row.saleId)">生成委外订单</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

        </div>
        <div class="avue-crud__pagination">
          <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
          </el-pagination>
        </div>
      </el-tab-pane>
      <el-tab-pane label="已生成委外订单" name="tab2">
        <el-form inline label-width="100px" @keyup.enter.native="searchHandle">
          <el-form-item label="单据编号">
            <el-input v-model="dataForm.billId"></el-input>
          </el-form-item>
          <el-form-item label="配镜单号">
            <el-input v-model="dataForm.saleBillId"></el-input>
          </el-form-item>
          <el-form-item label="制单人">
            <el-input v-model="dataForm.createUserName"></el-input>
          </el-form-item>
          <el-form-item label="制造商">
            <el-input v-model="dataForm.supplyName">
              <el-button slot="append" @click="openSupplyDialog">选择</el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="审核人">
            <el-input v-model="dataForm.auditUserName"></el-input>
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select v-model="dataForm.auditStatus">
              <el-option label="未审核" value="0"></el-option>
              <el-option label="已审核" value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品名称">
            <el-input v-model="dataForm.viewGoodsName"></el-input>
          </el-form-item>
          <el-form-item label="制单日期">
            <el-row>
              <el-col :span="11">
                <el-date-picker v-model="dataForm.createTimeStart" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
              <el-col class="line" :span="2" style="text-align: center;">-</el-col>
              <el-col :span="11">
                <el-date-picker v-model="dataForm.createTimeEnd" style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item label="单据类型">
            <el-select v-model="dataForm.consignType">
              <el-option value="1" label="隐形订做片"></el-option>
              <el-option value="2" label="框镜订做片"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="顾客姓名">
            <el-input v-model="dataForm.customerName"></el-input>
          </el-form-item>
        </el-form>

        <div class="avue-crud">
          <el-table :data="secondList" border v-loading="dataListLoading" :max-height="tableHeight2" @selection-change="handleSelectionChange">
            <el-table-column key="1" type="selection" width="30"></el-table-column>
            <el-table-column key="2" label="操作" width="380" fixed="right">
              <template slot-scope="scope">
                <el-button v-if="permissions.eims_consign_edit" type="text" icon="el-icon-edit" :disabled="scope.row.auditStatus == 1"
                  @click="consignUpdate(scope.row.id)">修改</el-button>
                <el-button v-if="permissions.eims_consign_del" type="text" icon="el-icon-edit" :disabled="scope.row.consignStatus == 2"
                  @click="cancelConsign(scope.row)">撤销委外订单</el-button>
                <el-button v-if="permissions.eims_consign_add" type="text" icon="el-icon-refresh" @click="openAgainDialog(scope.row)">重新生成订单</el-button>
                <el-button type="text" icon="el-icon-collection" @click="openDialogConsignInfo(scope.row.id)">查看详情</el-button>
              </template>
            </el-table-column>
            <el-table-column key="3" prop="billId" label="单据编号" width="160"></el-table-column>
            <el-table-column key="4" prop="saleBillId" label="配镜单号" width="160">
              <template slot-scope="scope">
                <el-button type="text" @click="checkDetailByOrder(scope.row.saleBillId)">{{scope.row.saleBillId}}</el-button>
              </template>
            </el-table-column>
            <el-table-column key="5" prop="customerName" label="顾客姓名" width="120"></el-table-column>
            <el-table-column key="6" prop="consignType" label="采购类型" width="80">
              <template slot-scope="scope">
                <!-- 1-隐形订做,2-框镜订做,3-隐形成品,4-框镜成品,5-辅料-->
                {{getSaleType(scope.row.consignType)}}
              </template>
            </el-table-column>
            <el-table-column key="7" prop="supplyName" label="制造商" width="120"></el-table-column>
            <el-table-column key="8" prop="createUserName" label="制单人" width="70"></el-table-column>
            <el-table-column key="9" prop="createTime" label="制单日期" width="135"></el-table-column>
            <el-table-column key="10" prop="auditUserName" label="审核人" width="70"></el-table-column>
            <el-table-column key="11" prop="auditTime" label="审核时间" width="135"></el-table-column>
            <el-table-column key="12" prop="memo" label="备注"> </el-table-column>

          </el-table>
        </div>
        <div class="avue-crud__pagination">
          <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex" :page-sizes="[10, 20, 50, 100, 200]" :page-size="pageSize" :total="totalPage" background layout="total, sizes, prev, pager, next">
          </el-pagination>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 弹窗, 生成委外订单 / 委外订单详情 -->
    <consign-add v-if="consignAddVisible" ref="consignAdd" @refreshDataList="getDataList"></consign-add>
    <consign-info v-if="consignInfoVisible" ref="consignInfo" @refreshDataList="getDataList"></consign-info>
    <!-- 弹窗, 批量生成委外订单 -->
    <!-- <outsource-batch v-if="outsourceBatchVisible" ref="outsourceBatch" @refreshDataList="getDataList"></outsource-batch>-->
    <!-- 弹窗, 新增 / 修改委外订单 -->
    <add-update v-if="updateVisible" ref="updateDialog" @refreshDataList="getDataList"></add-update>
    <!-- 弹窗，制造商选择 -->
    <search-supply v-if="supplyVisible" ref="supplyDialog" @refreshData="getSupplyData"></search-supply>
    <!-- 生成重订单 -->
    <order-again v-if="againVisible" ref="againDialog" @refreshData="getGoodsData"></order-again>
    <!-- 弹窗，查看配镜单详情 -->
    <order-info v-if="infoVisible" ref="infoDialog"></order-info>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import { remote } from '@/api/admin/dict'
  import { receiveApplyFetchList } from '@/api/eims/purchase/receive-apply'
  import { receiveGoodsFetchList, receiveGoodsDelObj } from '@/api/eims/purchase/receive-goods'
  import {
    getUnConsignSaleByPage,
    getConsignByPage,exportExcel,
    cancelConsignById
  } from '@/api/eims/consign/consignOrder'
  import { getDeptInfoByDeptType } from '@/api/admin/dept'
  import { getSupplyListByIds } from '@/api/eims/supply'
  import { getSupplyIdsByCtgIds } from '@/api/eims/supply-ctg'

  import ConsignAdd from './components/consign-add'
  import ConsignInfo from './components/consign-info'
  //import OutsourceBatch from './components/outsource-batch.vue'
  // 弹窗， 新增 / 修改 委外订单
  import AddUpdate from './components/add-update'
  import SearchSupply from '@/components/business/SearchSupply'

  import OrderAgain from './components/OrderAgain'
  import OrderInfo from '@/views/eims/optician/glassesinfo/detail'

  export default {
    data() {
      return {
        tabValue: 'tab1',
        dataForm: {
          saleBillId: ''
        },
        deptOption: [],
        saleTypeData: [],
        saleTypeOptions: [{
            label: '框镜订做片',
            value: '2'
          },
          {
            label: '隐形订做片',
            value: '1'
          }
        ],
        firstList: [],
        secondList: [],
        pageIndex: 1,
        pageSize: 200,
        totalPage: 0,
        dataListLoading: false,
        orderList: [],
        consignAddVisible: false,
        consignInfoVisible: false,
        outsourceBatchVisible: false,
        updateVisible: false,
        supplyVisible: false,
        againVisible: false,
        infoVisible: false,
        timeOptionStart: {},
        timeOptionEnd: {},
        supplyOptions: []
      }
    },
    components: {
      ConsignAdd, //委外订单新增页面
      ConsignInfo, //委外订单详情页面
      //OutsourceBatch,
      AddUpdate,
      SearchSupply,
      OrderAgain,
      OrderInfo
    },
    created() {
      this.getDataList()
      this.getDeptList()
      this.getSupplyIds()
      remote('sale_type').then(result => {
        this.saleTypeData = result.data.data
      })
    },
    computed: {
      ...mapGetters(['permissions', 'bizData', 'userInfo']),
      tableHeight: function(){
        return window.innerHeight - 260
      },
      tableHeight2: function(){
        return window.innerHeight - 260
      }
    },
    methods: {
      tabChange(data) {
        for (let key in this.dataForm) {
          this.dataForm[key] = ''
        }
        this.getDataList()
        this.pageIndex = 1
        this.firstList = []
        this.secondList = []
        if (this.tabValue == 'tab1') {
          this.getDeptList()
        }
      },
      exportExcel() {
          let params2 = this.filterParams(this.dataForm)
          exportExcel(params2).then(response => {
            var blob = new Blob([response.data], {
                type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            });
            var reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onload = function(e) {
                var a = document.createElement('a');
                a.download = "委外订单详情.xlsx";
                a.href = URL.createObjectURL(blob);
                a.click();
            }
          })
      },
      //	查询数据
      searchHandle() {
        this.pageIndex = 1
        this.getDataList()
      },
      getDataList() {
        let params1 = {
          current: this.pageIndex,
          size: this.pageSize
        }
        let params2 = this.filterParams(this.dataForm)
        this.dataListLoading = true
        if (this.tabValue == 'tab1') {
          getUnConsignSaleByPage(Object.assign(params1, params2)).then(response => {
            if(response.data.code == '0'){
              this.firstList = response.data.data.records
              this.totalPage = response.data.data.total
            }else{
              this.$message.error(response.data.msg)
            }
            this.dataListLoading = false
          })
        } else if (this.tabValue == 'tab2') {
          getConsignByPage(Object.assign(params1, params2)).then(response => {
            if(response.data.code == '0'){
              this.secondList = response.data.data.records
              this.totalPage = response.data.data.total
            }else{
              this.$message.error(response.data.msg)
            }
            this.dataListLoading = false
          })
        }
      },
      // 每页显示条数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      handleSelectionChange(val) {
        this.orderList = val
      },
      //  打开弹窗, 生成委外订单
      openDialogConsignAdd(id) {
        this.consignAddVisible = true
        this.$nextTick(() => {
          this.$refs.consignAdd.init(id)
        })
      },
      //  打开弹窗，修改委外订单
      consignUpdate(id) {
        this.updateVisible = true
        this.$nextTick(() => {
          this.$refs.updateDialog.init(id)
        })
      },
      //  打开弹窗, 查看委外订单详情
      openDialogConsignInfo(id) {
        this.consignInfoVisible = true
        this.$nextTick(() => {
          this.$refs.consignInfo.init(id)
        })
      },
      //  打开弹窗，生成重订单
      openAgainDialog(data) {
        this.againVisible = true
        this.$nextTick(() => {
          this.$refs.againDialog.init(data)
        })
      },
      //撤销委外订单
      cancelConsign(data) {
        this.$confirm("是否确认撤销委外单号为" + data.billId + "的委外订单", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          })
          .then(function() {
            return cancelConsignById(data.id);
          })
          .then(response => {
            if(response.data.code == '0'){
              this.$message.success("撤销成功");
              this.getDataList();
            }else{
              this.$message.error(response.data.msg)
            }

          });
      },
      //获取配镜类型枚举
      getSaleType(value) {
        let obj = {};
        obj = this.saleTypeData.find((item) => {
          return item.value == value;
        });
        if (obj && obj.label) {
          return obj.label;
        }
      },
      // 打开弹窗， 新增 / 修改 委外订单
      openDialogAddUpdate(id) {
        this.addUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addUpdate.init(id)
        })
      },
      // 打开采购订单弹窗
      orderReceiveGoods(id) {
        this.receiveGoodsVisible = true
        this.$nextTick(() => {
          this.$refs.receiveGoods.init(id)
        })
      },
      //  打开弹窗，查看配镜单详情
      checkDetailByOrder(order) {
        this.infoVisible = true;
        this.$nextTick(() => {
          this.$refs.infoDialog.init('', order, '配镜单详情');
        });
      },
      // 搜索清空
      searchReset() {
        for (let key in this.dataForm) {
          this.dataForm[key] = ''
        }
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 隐形新增
      addOrUpdateHandleInvisible() {
        this.invisibleFormVisible = true
        this.$nextTick(() => {
          this.$refs.invisibleForm.init()
        })
      },
      // 删除
      deleteHandle(id) {
        this.$confirm('是否确认删除ID为' + id, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function() {
          return receiveGoodsDelObj(id)
        }).then(response => {
          if(response.data.code == '0'){
            this.$message.success('删除成功')
            this.getDataList()
          }else{
            this.$message.error(response.data.msg)
          }

        })
      },
      //   打开制造商选择弹窗
      openSupplyDialog() {
        this.supplyVisible = true
        this.$nextTick(() => {
          this.$refs.supplyDialog.init({
            ctgId: ''
          })
        })
      },
      //   获取制造商信息
      getSupplyData(data) {
        this.$set(this.dataForm, 'supplyName', data.name)
        this.$set(this.dataForm, 'supplyId', data.id)
      },
      //  获取配镜单商品信息
      getGoodsData(data) {

      },
      timeChangeStart() {
        this.timeOptionStart = Object.assign({}, this.timeOptionStart, {
          disabledDate: (time) => {
            if (this.dataForm.createTimeEnd) {
              return time.getTime() > this.dataForm.createTimeEnd
            } else {
              return false
            }
          }
        })
      },
      timeChangeEnd() {
        this.timeOptionEnd = Object.assign({}, this.timeOptionEnd, {
          disabledDate: (time) => {
            if (this.dataForm.createTimeStart) {
              return time.getTime() < this.dataForm.createTimeStart
            } else {
              return false
            }
          }
        })
      },
      getDeptList() {
        getDeptInfoByDeptType(1).then(result => {
          this.deptOption = result.data.data
        })
      },
      //获取镜片和隐形的制造商id集合
      getSupplyIds() {
        var ctgList = []
        ctgList.push(3);
        ctgList.push(4)
        var supplyIds = []
        getSupplyIdsByCtgIds({
          ctgIds: ctgList
        }).then(result => {
          getSupplyListByIds({
            ids: result.data.data
          }).then(result2 => {
            this.supplyOptions = result2.data.data
          })
        })

      },
    }
  }
</script>
